package com.j.app.dim;/**
 * @ClassName DimApp
 * @Description Dim层代码
 * @date 2024/3/4 20:56
 * @Author JG
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.j.app.function.DimSinkFunction;
import com.j.app.function.TableProcessFunction;
import com.j.bean.TableProcess;
import com.j.utils.MyKafkaUtil;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import com.ververica.cdc.connectors.mysql.table.StartupOptions;
import com.ververica.cdc.debezium.JsonDebeziumDeserializationSchema;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.table.descriptors.Json;
import org.apache.flink.util.Collector;

/**
 * 1.获取执行环境
 * 2.读取kafka，创建主流
 * 3.对数据进行过滤，过滤非json数据以及保留新增变化初始化数据
 * 4.使用flinkCDC读取mysql配置信息表创建配置流
 * 5.将配置流创建广播流
 * 6.连接主流与广播流
 * 7.处理连接流，根据配置信息处理主流数据
 * 8.写出数据
 * 9.启动任务
 */
public class DimApp {
    public static void main(String[] args) throws Exception {
        //TODO 1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);//生产环境设置为kafka主题的分区数量
        //1.1开启checkpoint
        env.enableCheckpointing(5*6000L, CheckpointingMode.EXACTLY_ONCE);
        env.getCheckpointConfig().setCheckpointTimeout(10*6000L);
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
        env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3,5000L));
        //1.2设置状态后端
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop100:8020/flink/gmall");
        System.setProperty("HADOOP_USEER_NAME","root");

        //TODO 2.读取kafka，创建主流
        String topic="topic_db";
        String groupid="Dim_App_240304";
        DataStreamSource<String> kafkaDS = env.addSource(MyKafkaUtil.GetFlinkKafkaConsumer(topic, groupid));

        //TODO 3.对数据进行过滤，过滤非json数据以及保留新增变化初始化数据并且转换为json格式
        SingleOutputStreamOperator<JSONObject> filterJsonObjDS = kafkaDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                try {
                    JSONObject jsonObject = JSON.parseObject(s);
                    String type = jsonObject.getString("type");
                    if ("insert".equals(type) || "update".equals(type) || "bootstrap-insert".equals(type)) {
                        collector.collect(jsonObject);
                    }
                } catch (Exception e) {
                    System.out.println("发现脏数据" + s);
                }
            }
        });

        /**数据格式
         * {"database":"gmall","table":"base_trademark","type":"insert","ts":1709600738,"xid":395,"commit":true,"data":{"id":13,"tm_name":"j","logo_url":"aaaa/aaaa"}}
         * {"database":"gmall","table":"base_trademark","type":"update","ts":1709600771,"xid":474,"commit":true,"data":{"id":13,"tm_name":"j","logo_url":"/bbbb/"},"old":{"logo_url":"aaaa/aaaa"}}
         * {"database":"gmall","table":"base_trademark","type":"delete","ts":1709600782,"xid":503,"commit":true,"data":{"id":13,"tm_name":"j","logo_url":"/bbbb/"}}
         *
         * {"database":"gmall","table":"base_trademark","type":"bootstrap-start","ts":1709600943,"data":{}}
         * {"database":"gmall","table":"base_trademark","type":"bootstrap-insert","ts":1709600943,"data":{"id":1,"tm_name":"三星","logo_url":"/static/default.jpg"}}
         * {"database":"gmall","table":"base_trademark","type":"bootstrap-insert","ts":1709600943,"data":{"id":2,"tm_name":"苹果","logo_url":"/static/default.jpg"}}
         */

        //TODO 4.使用flinkCDC读取mysql配置信息表创建配置流
        MySqlSource<String>  mySqlSource = MySqlSource.<String>builder()
                .hostname("hadoop100")
                .port(3306)
                .username("root")
                .password("jg12138JG")
                .databaseList("gamall-config")
                .tableList("gamall-config.table_process")
                .startupOptions(StartupOptions.initial())
                .deserializer(new JsonDebeziumDeserializationSchema())
                .build();

        DataStreamSource<String> mysqlSourceDS = env.fromSource(mySqlSource, WatermarkStrategy.noWatermarks(), "MysqlSource");

        //TODO 5.将配置信息流处理为广播流
        MapStateDescriptor<String, TableProcess> stringTableProcessMapStateDescriptor = new MapStateDescriptor<>("map-state", String.class, TableProcess.class);
        BroadcastStream<String> broadcastStream=mysqlSourceDS.broadcast(stringTableProcessMapStateDescriptor);

        //TODO 6.链接主流与广播流
        BroadcastConnectedStream<JSONObject,String> connectedStream =filterJsonObjDS.connect(broadcastStream);
        //TODO 7.处理连接流
        SingleOutputStreamOperator<JSONObject> dimDS = connectedStream.process(new TableProcessFunction(stringTableProcessMapStateDescriptor));
        dimDS.addSink(new DimSinkFunction());

        //TODO 9.启动任务
        env.execute();

     }


}
